//variables
var time = time;
var timestamp = timestamp;
var intervall = intervall;
var downloadbutton_link_button_text = 'Descargar';

var RecaptchaOptions = {
		    theme : 'custom',
		    custom_theme_widget: 'recaptcha_widget'
		 };


var filetype = filetype;
var waitingtime = waitingtime;
var blocktime = blocktime;
var captcha = captcha;
var ajaxdl = ajaxdl;
var mp4 =  mp4;
var archivoID = location.href.split("=");  
archivoID = archivoID[1];
//fin de variables

//elimina las funciones por defecto
var c = document.getElementsByTagName('script'); c = c[4];
c.parentNode.removeChild(c);
//fin de elimira funciones

//funciones
var popupblocktime = 20; //minutes
var popupurl = 'http://ad.xtendmedia.com/imp?z=0&Z=0x0&s=2579665&y=23&w=800&h=600&t=3';

var iframesrc_captcha = 'http://bitshare.com/getiframepopup_download.html';


function errorHandler(msg) {
    alert('An error has occured:' + msg);
}

function runde(x, n) {
  if (n < 1 || n > 14) return false;
  var e = Math.pow(10, n);
  var k = (Math.round(x * e) / e).toString();
  if (k.indexOf('.') == -1) k += '.';
  k += e.toString().substring(1);
  return k.substring(0, k.indexOf('.') + n+1);
}

function calculateTime(secs) {
	var out;

	if(secs > 3600) {
		out = Math.floor(secs/3600) + ' Hours, ' + Math.floor(secs/60) + ' Minutes, ' + Math.round(secs % 60) + 'Seconds';
	} else if(secs > 60) {
		out = Math.floor(secs/60) + ' Minutes, ' + Math.round(secs % 60) + ' Seconds';
	} else {
		out = Math.round(secs) + ' Seconds';
	}

	return out;
}

function timer() {
    //time = runde(time - 0.1,1);

    time = runde((timestamp - new Date().getTime()) / 1000, 1);

    $('#counter').html(time);
    if(time <= 0) {
        clearInterval(intervall);

        waitingtime = 0;
       	stepHandler();

    }
}

function blocktimer() {
    blocktime = runde(blocktime - 0.1, 1);

    $('#blocktimecounter').html(calculateTime(blocktime));
    if(blocktime <= 0) {
        clearInterval(blocktimeintervall);

        $('#blocktime').hide();

      	$('#disableddownloadbutton').hide();
        startDownloadPremium();

    }
}

function goToDownloadUrl() {

	$.ajax({
	   type: "POST",
	   dataType: "html",
	   cache: false,
	   error:function(xhr, status, errorThrown) {
	    	$('#testdiv').html('Error Thrown: '+errorThrown+'<br />Status: '+status+'<br />XHR StatusText:'+xhr.statusText+'<br />XHR Status:'+xhr.status);
            //alert('An error occured. Please try again. (' + xhr.responseText + ' / ' + status + ') ');

            console.log("xhr.status: " + xhr.status);
            console.log("xhr.statusText: " + xhr.statusText);
            console.log("xhr.readyState: " + xhr.readyState);
            console.log("xhr.responseText: " + xhr.responseText);
            console.log("xhr.responseXML: " + xhr.responseXML);
            console.log("textStatus: " + textStatus);
            console.log("errorThrown: " + errorThrown);
            console.log("xhr.redirect: " + xhr.redirect);

       },
	   url: "http://bitshare.com/files-ajax/"+archivoID+"/request.html",
	   data: "request=getDownloadURL&ajaxid="+ajaxdl,
	   success:
	    function(data){
                	//alert(data);
                    var tmp = data.split('#');
                    if(tmp[0] == 'ERROR') {
                        $('#errorbox').html(tmp[1]);
                        $('#errorbox').show();
                    } else {
                        $('#downloadbutton_link').attr('href', tmp[1]);


                        $('#downloadbutton_link_button').removeClass('graybutton');
                    	$('#downloadbutton_link_button').addClass('bluebutton');

                       $('#downloadbutton_link_button_text').html(downloadbutton_link_button_text);
                    	//window.location =  tmp[1];
                    }
                   }
	 });

	/*$.post(    "http://bitshare.com/files-ajax/"+archivoID+"/request.html",
                { request: "getDownloadURL", ajaxid: ajaxdl },
                function(data){
                	//alert(data);
                    var tmp = data.split('#');
                    if(tmp[0] == 'ERROR') {
                        $('#errorbox').html(tmp[1]);
                        $('#errorbox').show();
                    } else {
                    	window.location =  tmp[1];
                    }
    });*/

}

function stepHandler() {

	$('.dlbox').hide();

	 if(waitingtime > 0) {
         timestamp = new Date().getTime() + (waitingtime*1000);
	 	 $('#benefit-waitingtime').show();
		 $('#counter').html(waitingtime);
		 time = parseFloat(waitingtime);
		 $('#waitingtime').show();
		 intervall = window.setInterval("timer()", 100);

	 } else if (captcha == 1) {
	 	$('#captcha').show();


        if(mp4 == true) {
        } else {
            iframe = document.getElementById('adsiframe');
            iframe.src = iframesrc_captcha + "?anticache=" + Date.parse(new Date());
        }



	 	/* Advertising
        $('#captcha_advertising').html(captcha_advertising);
        $('#captcha_advertising').show();
		$('#captcha_advertising_right').html(captcha_advertising_right);
        $('#captcha_advertising_right').show();

		$('#captcha_advertising').show();*/


	 } else {
		// Download starten
        if(mp4 == true) {
            $('#stream_player').show();
            //Ads Stream
            $('#adblock_player_right').show();
            $('#adblock_player_right_iframe').show();
            //$('#adblock_player_left').show();

            // Extension for embedded popup
            /*if(typeof embedded_iframe_popup != "undefined") {
                 iframe = document.getElementById('embedded_adsiframe');
                 iframe.src = embedded_iframe_popup + "?anticache=" + Date.parse(new Date());
            }*/
        } else {

             $('#downloadbutton_link_button').removeClass('bluebutton');
             $('#downloadbutton_link_button').addClass('graybutton');

             $('#downloadbutton_link_button_text').html('Loading...');

            $('#downloadstarting').show();
            goToDownloadUrl();
        }





		// Advertisment
		//$('#captcha_advertising').html(" ");
		//$('#captcha_advertising').hide();
		//$('#downloadstarting_advertising').html(downloadstarting_advertising);
		//$('#downloadstarting_advertising').show();
	 }
}

function startDownload() {
    // request der DL ID starten

    $('#disableddownloadbuttonwaiting').show();
    $('#activdownloadbutton').hide();

    $.ajax({
	   type: "POST",
	   dataType: "html",
	   cache: false,
	    error:function(xhr, status, errorThrown) {
	    	$('#testdiv').html(errorThrown+'<br />'+status+'<br />'+xhr.statusText);


        },
	   url: "http://bitshare.com/files-ajax/"+archivoID+"/request.html",
	   data: "request=generateID&ajaxid="+ajaxdl,
	   success:
	    function(data){
                	$('#testdiv').html(data);
                    var tmp = data.split(':');
					//alert(data);
                    if(tmp[0] == 'ERROR') {
                        errorHandler(tmp[1]);

                        $('#disableddownloadbuttonwaiting').hide();
      					$('#activdownloadbutton').show();

                    } else {
                    	//alert(data);

                    	 $('#disableddownloadbuttonwaiting').hide();
						 $('#disableddownloadbutton').show();


                    	filetype = tmp[0];
                    	waitingtime = tmp[1];
                    	captcha = tmp[2];

                    	stepHandler();
                    }
                   }

	 });

     /*$.post(    "http://bitshare.com/files-ajax/"+archivoID+"/request.html",
                { request: "generateID", ajaxid: ajaxdl },
                function(data){
                	$('#testdiv').html(data);
                    var tmp = data.split(':');
                    if(tmp[0] == 'ERROR') {
                        errorHandler(tmp[1]);

                        $('#disableddownloadbuttonwaiting').hide();
      					$('#activdownloadbutton').show();

                    } else {
                    	//alert(data);

                    	 $('#disableddownloadbuttonwaiting').hide();
						 $('#disableddownloadbutton').show();


                    	filetype = tmp[0];
                    	waitingtime = tmp[1];
                    	captcha = tmp[2];

                    	stepHandler();
                    }
                   });*/

}

function stepHandlerPremium() {

	$('.dlbox').hide();

	 if(waitingtime > 0) {
	 	 $('#benefit-waitingtime').show();
		 $('#counter').html(waitingtime);
		 time = parseFloat(waitingtime);
		 $('#waitingtime').show();
		 intervall = window.setInterval("timer()", 100);

	 } else if (captcha == 1) {
	 	$('#captcha').show();
	 } else {
		// Download starten
		$('#downloadstarting').show();
		goToDownloadUrlPremium();
	 }
}
function goToDownloadUrlPremium() {

	$.ajax({
	   type: "POST",
	   dataType: "html",
	   cache: false,
	    error:function(xhr, status, errorThrown) {
	    	$('#testdiv').html(errorThrown+'<br />'+status+'<br />'+xhr.statusText);


        },
	   url: "http://bitshare.com/files-ajax/"+archivoID+"/request.html",
	   data: "request=getDownloadURL&ajaxid="+ajaxdl,
	   success:
	    function(data){
                	//alert(data);
                    var tmp = data.split('#');
                    if(tmp[0] == 'ERROR') {
                        $('#errorbox').html(tmp[1]);
                        $('#errorbox').show();
                    } else {
                    	$('#downloadbutton_link').attr('href', tmp[1]);
                    	window.location =  tmp[1];
                    }
                   }
	 });

	/*$.post(    "http://bitshare.com/files-ajax/"+archivoID+"/request.html",
                { request: "getDownloadURL", ajaxid: ajaxdl },
                function(data){
                	//alert(data);
                    var tmp = data.split('#');
                    if(tmp[0] == 'ERROR') {
                        $('#errorbox').html(tmp[1]);
                        $('#errorbox').show();
                    } else {
                    	window.location =  tmp[1];
                    }
    });*/

}
function startDownloadPremium() {
    // request der DL ID starten

    $('#disableddownloadbuttonwaiting').show();
    $('#activdownloadbutton').hide();

    $.ajax({
	   type: "POST",
	   dataType: "html",
	   cache: false,
	    error:function(xhr, status, errorThrown) {
	    	$('#testdiv').html(errorThrown+'<br />'+status+'<br />'+xhr.statusText);


        },
	   url: "http://bitshare.com/files-ajax/"+archivoID+"/request.html",
	   data: "request=generateID&ajaxid="+ajaxdl,
	   success:
	    function(data){
                	$('#testdiv').html(data);
                    var tmp = data.split(':');
                    if(tmp[0] == 'ERROR') {
                        errorHandler(tmp[1]);

                        $('#disableddownloadbuttonwaiting').hide();
      					$('#activdownloadbutton').show();

                    } else {
                    	//alert(data);

                    	 $('#disableddownloadbuttonwaiting').hide();
						 $('#disableddownloadbutton').show();


                    	filetype = tmp[0];
                    	waitingtime = tmp[1];
                    	captcha = tmp[2];

                    	stepHandlerPremium();
                    }
                   }

	 });

}

function validateCaptcha() {
	$.ajax({
	   type: "POST",
	   dataType: "html",
	   cache: false,
	    error:function(xhr, status, errorThrown) {
	    	$('#testdiv').html(errorThrown+'<br />'+status+'<br />'+xhr.statusText);


        },
	   url: "http://bitshare.com/files-ajax/"+archivoID+"/request.html",
	   data: "request=validateCaptcha&ajaxid="+ajaxdl+"&recaptcha_challenge_field="+$("input#recaptcha_challenge_field").val()+"&recaptcha_response_field="+$("input#recaptcha_response_field").val() ,
	   success:
	    function(data){
                	var tmp = data.split(':');
                    if(tmp[0] == 'SUCCESS') {
                        // recaptcha success
                        $('#captchawrong').hide();
                        captcha = 0;
						stepHandler();
                    } else {
                    	//errorHandler(tmp[1]);
                    	$('#captchawrong').show('fast');
						Recaptcha.reload();
					}
        }

	 });

}

function openPopUp() {

//consolelog
console.log("lo uq uqwrua");



}

function disableButton() {
    $('#submit').attr("disabled", true);
    $('#submit').css('color', '#9b978f');
}



function createCookie(name,value,minutes) {
    if (minutes) {
        var date = new Date();
        date.setTime(date.getTime()+(minutes*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

startDownload();